package com.bestcem.xm.user.service.impl.init;

import com.alibaba.fastjson.JSONArray;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.user.config.properties.SettingProperties;
import com.bestcem.xm.user.config.properties.SingleOrgProperties;
import com.bestcem.xm.user.config.properties.UserEmailProperties;
import com.bestcem.xm.user.constant.UserCacheKeyConstant;
import com.bestcem.xm.user.dao.OrganizationDao;
import com.bestcem.xm.user.entity.pojo.UserDO;
import com.bestcem.xm.user.enums.*;
import com.bestcem.xm.user.grpc.client.IndustryGrpcService;
import com.bestcem.xm.user.grpc.client.MessageCenterService;
import com.bestcem.xm.user.grpc.client.UserWalletGrpcService;
import com.bestcem.xm.user.grpc.client.dto.IndustryDTO;
import com.bestcem.xm.user.mq.send.biz.UserMessageSendService;
import com.bestcem.xm.user.service.*;
import com.bestcem.xm.user.service.dto.group.UserGroupDTO;
import com.bestcem.xm.user.service.dto.init.InitOrgRequestDTO;
import com.bestcem.xm.user.service.dto.role.UserRoleDTO;
import com.bestcem.xm.user.service.dto.user.*;
import com.bestcem.xm.user.service.init.UserInitService;
import com.bestcem.xm.user.util.business.FileUtils;
import com.bestcem.xm.user.util.business.PwdUtil;
import com.bestcem.xm.user.util.business.UserCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 用户中心初始化服务
 *
 * @author wangyunyun <yunyun.wang@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/18 18:37
 */
@Slf4j
@Service
public class UserInitServiceImpl implements UserInitService {

    @Autowired
    private UserEmailProperties userEmailProperties;

    @Autowired
    private UserCacheUtil userCacheUtil;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private MessageCenterService messageCenterService;
    @Autowired
    private UserSmtpService userSmtpService;
    @Autowired
    private UserMfaSettingService userMfaSettingService;
    @Autowired
    private RoleService roleService;
    @Resource
    private UserService userService;
    //    @Resource
//    private InitDataService initDataService;
    @Resource
    private IndustryGrpcService industryGrpcService;
    @Autowired
    private UserUserRoleService userUserRoleService;
    @Resource
    private UserGroupService userGroupService;
    @Resource
    private SequenceService sequenceService;

    @Resource
    private UserWalletGrpcService userWalletGrpcService;

    @Resource
    private OrganizationDao organizationDao;

    //@Autowired
    //private OrganizationMessageSender organizationMessageSender;

    @Resource
    private UserMessageSendService userMessageSendService;

    @Resource
    private SingleOrgProperties singleOrgProperties;
    @Resource
    private SettingProperties settingProperties;

    @Override
    public ServiceResult<UserRoleDTO> initAdminRoleAndPerms(String orgId) {
        // 校验参数
        if (StringUtils.isBlank(orgId)) {
            return ServiceResult.fail("参数为空");
        }
        // 查询并校验公司
        OrganizationDTO organizationDTO = organizationService.selectByPrimaryKey(orgId).getData();
        if (organizationDTO == null) {
            return ServiceResult.fail(String.format("公司不存在, orgId = [%s]", orgId));
        }

        return roleService.createOrUpdateRoleAndPerms(orgId, RolePermsEnum.ADMIN);
    }

    @Override
    public ServiceResult<Void> resetUserPwd(String orgCode, String userName, String password) {
        ServiceResult<OrganizationDTO> result = organizationService.selectByOrgCode(orgCode);
        OrganizationDTO org = result.getData();
        if (!result.isSuccess() || Objects.isNull(org)) {
            return ServiceResult.fail(String.format("orgCode:%s不正确", orgCode));
        }

        UserDTO dto = new UserDTO();
        dto.setOrgId(org.getOrgId());
        dto.setUserName(userName);
        ServiceResult<List<UserDO>> listServiceResult = userService.selectByOrgIdSelective(dto);
        List<UserDO> userDOS = listServiceResult.getData();
        if (listServiceResult.isSuccess() && CollectionUtils.isNotEmpty(userDOS)) {
            ServiceResult<String> resetPassword = userService.resetPassword(userDOS.get(0).getUserId(), password);
            if (!resetPassword.isSuccess()) {
                return ServiceResult.fail(resetPassword.getMsg());
            }
            return ServiceResult.success();
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<Void> initOrganizationAsyncTask(String orgId) {
        userMessageSendService.userOrgCreate(orgId);
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<Void> delValidateFailSmtp() {
        UserSmtpDTO userSmtpDTO = new UserSmtpDTO();
        userSmtpDTO.setValidateStatus(UserSmtpValidateStatusEnum.VERIFIED_FAILED.getStatus());
        userSmtpService.deleteBySelective(userSmtpDTO);
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<Void> addSystemSmtp() {
        UserSmtpDTO smtpDTO = new UserSmtpDTO();
        smtpDTO.setAccount(userEmailProperties.getDefaultEmail())
                .setPassword(userEmailProperties.getDefaultPwd())
                .setHost(userEmailProperties.getDefaultHost())
                .setPort(userEmailProperties.getDefaultPort())
                .setDescription("倍市得系统邮箱")
                .setSslFlag(UserEnum.USER_YES.getFlag())
                .setValidateStatus(UserSmtpValidateStatusEnum.VERIFIED_SUCCESS.getStatus())
                .setDeliverFlag(UserEnum.USER_NO.getFlag())
                .setNoticeFlag(UserEnum.USER_YES.getFlag())
                .setSystemFlag(UserEnum.USER_YES.getFlag());

        // 查询所有公司
        OrganizationDTO organizationDTO = new OrganizationDTO();
        ServiceResult<List<OrganizationDTO>> orgResult = organizationService.selectBySelective(organizationDTO);
        for (OrganizationDTO org : orgResult.getData()) {
            smtpDTO.setOrgId(org.getOrgId());

            UserSmtpDTO userSmtpDTO = new UserSmtpDTO();
            userSmtpDTO.setOrgId(org.getOrgId())
                    .setSystemFlag(UserEnum.USER_YES.getFlag());
            ServiceResult<List<UserSmtpDTO>> systemResult = userSmtpService.selectBySelective(userSmtpDTO);
            if (CollectionUtils.isEmpty(systemResult.getData())) {
                // 不存在系统邮箱
                userSmtpDTO.setOrgId(org.getOrgId())
                        .setNoticeFlag(UserEnum.USER_YES.getFlag());
                ServiceResult<List<UserSmtpDTO>> noticeResult = userSmtpService.selectBySelective(userSmtpDTO);
                if (CollectionUtils.isNotEmpty(noticeResult.getData())) {
                    // 如果已存在默认通知邮箱，则系统邮箱不设为默认
                    smtpDTO.setNoticeFlag(UserEnum.USER_NO.getFlag());
                }
                ServiceResult<String> result = userSmtpService.insertSelective(smtpDTO);
                org.setCheckSmtpId(result.getData());
                organizationService.updateOrg(org);
            } else {
                // 存在系统邮箱 则检查默认审核邮箱是否存在 不存在则将系统邮箱设置为默认审核邮箱
                if (StringUtils.isBlank(org.getCheckSmtpId())) {
                    log.info("设置默认审核邮箱 id:{}", systemResult.getData().get(0).getSmtpId());
                    org.setCheckSmtpId(systemResult.getData().get(0).getSmtpId());
                    organizationService.updateOrg(org);
                }
            }
        }

        return ServiceResult.success();
    }

    @Override
    public ServiceResult<UserRoleDTO> initSeniorAdminRoleAndPerms(String orgId) {
        // 校验参数
        if (StringUtils.isBlank(orgId)) {
            return ServiceResult.fail("参数为空");
        }
        // 查询并校验公司
        OrganizationDTO organizationDTO = organizationService.selectByPrimaryKey(orgId).getData();
        if (organizationDTO == null) {
            return ServiceResult.fail(String.format("公司不存在, orgId = [%s]", orgId));
        }

        return roleService.createOrUpdateRoleAndPerms(orgId, RolePermsEnum.SENIOR_ADMIN);
    }

    @Override
    public ServiceResult<Void> resetRolePerms(String roleName) {
        // 校验参数
        if (StringUtils.isBlank(roleName)) {
            return ServiceResult.fail("参数为空");
        }
        return roleService.resetRolePerms(roleName);
    }

    @Override
    public ServiceResult<UserMfaSettingDTO> initOrgMfaSetting() {
        if (Objects.nonNull(singleOrgProperties)) {
            ServiceResult<OrganizationDTO> organizationDTOServiceResult = organizationService.selectByOrgCode(singleOrgProperties.getCode());
            OrganizationDTO org = organizationDTOServiceResult.getData();
            if (organizationDTOServiceResult.isSuccess() && Objects.nonNull(org)) {
                ServiceResult<UserMfaSettingDTO> mfaSettingService = userMfaSettingService.getMfaSettingByOrgId(org.getOrgId());
                UserMfaSettingDTO userMfaSettingDTO = mfaSettingService.getData();
                if (mfaSettingService.isSuccess() && Objects.nonNull(userMfaSettingDTO)) {
                    // 更新租户mfa信息
                    UserMfaSettingDTO dto = new UserMfaSettingDTO();
                    dto.setId(userMfaSettingDTO.getId())
                            .setOrgId(org.getOrgId())
                            .setOpenMfa(BooleanStatusEnum.NO.getStatus())
                            .setAuthMethod(MfaSettingAuthMethodEnum.MFASETTING_AUTH_METHOD_SMS.getType())
                            .setAllowSkip(BooleanStatusEnum.NO.getStatus());
                    userMfaSettingService.updateById(dto);

                } else if (mfaSettingService.isSuccess() && Objects.isNull(userMfaSettingDTO)) {
                    // 初始化租户mfa信息
                    UserMfaSettingDTO dto = new UserMfaSettingDTO();
                    dto.setOrgId(org.getOrgId())
                            .setOpenMfa(BooleanStatusEnum.NO.getStatus())
                            .setAuthMethod(MfaSettingAuthMethodEnum.MFASETTING_AUTH_METHOD_SMS.getType())
                            .setAllowSkip(BooleanStatusEnum.NO.getStatus());
                    ServiceResult<Integer> insertSelective = userMfaSettingService.insertSelective(dto);
                    if (insertSelective.getData().equals(0)) {
                        return ServiceResult.fail("初始化租户mfaSetting失败 orgId:" + org.getOrgId());
                    }
                    ServiceResult<UserMfaSettingDTO> mfaSettingByOrgId = userMfaSettingService.getMfaSettingByOrgId(org.getOrgId());
                    if (mfaSettingByOrgId.isSuccess()) {
                        return ServiceResult.success(mfaSettingByOrgId.getData());
                    }
                }
            }
        }

        return ServiceResult.fail("获取单租户模式公司配置失败");
    }

    @Override
    public ServiceResult<Void> updateAdminAndSeniorRolePerms() {
        return roleService.resetAdminAndSeniorRole();
    }

    @Override
    public ServiceResult<Boolean> initFreeOrganization() {
        return organizationService.updateInitFreeOrg();
    }

    @Override
    public void initDefaultTemplate(String orgId) {
        messageCenterService.initDefaultTemplate(orgId);
    }

    @Override
    public ServiceResult<Boolean> updateAcceptAndInnerUser() {
        return userService.updateAcceptAndInnerUser();
    }

    private OrganizationDTO initOrgRequestDTOToDTO(InitOrgRequestDTO dto) {
        OrganizationDTO organizationDTO = new OrganizationDTO();

        if (StringUtils.isNotBlank(dto.getOrgId())) {
            organizationDTO.setOrgId(dto.getOrgId());
        }
        if (StringUtils.isNotBlank(dto.getCode())) {
            organizationDTO.setCode(dto.getCode());
        }
        if (StringUtils.isNotBlank(dto.getName())) {
            organizationDTO.setName(dto.getName());
        }
        if (StringUtils.isNotBlank(dto.getContent())) {
            organizationDTO.setContent(dto.getContent());
        }
        if (Objects.nonNull(dto.getStatus())) {
            organizationDTO.setStatus(dto.getStatus());
        } else {
            organizationDTO.setStatus(OrganizationStatusEnum.ACTIVATED.getStatus());
        }
        if (Objects.nonNull(dto.getSource())) {
            organizationDTO.setSource(dto.getSource());
        }
        if (StringUtils.isNotBlank(dto.getSourceRemark())) {
            organizationDTO.setSourceRemark(dto.getSourceRemark());
        }
        if (Objects.nonNull(dto.getFormalExpireTime())) {
            organizationDTO.setFormalExpireTime(dto.getFormalExpireTime());
        }
        if (Objects.nonNull(dto.getTrialExpireTime())) {
            organizationDTO.setTrialExpireTime(dto.getTrialExpireTime());
        }
        if (StringUtils.isNotBlank(dto.getEmail())) {
            organizationDTO.setAdminEmail(dto.getEmail());
        }
        if (StringUtils.isNotBlank(dto.getMobile())) {
            organizationDTO.setAdminPhone(dto.getMobile());
        }
        if (Objects.nonNull(dto.getExpireDt())) {
            organizationDTO.setPackageExpireTime(dto.getExpireDt());
        }
        if (Objects.nonNull(dto.getFreeExpireTime())) {
            organizationDTO.setFreeExpireTime(dto.getFreeExpireTime());
        }
        if (StringUtils.isNotBlank(dto.getSkin())) {
            organizationDTO.setSkin(dto.getSkin());
        }
        if (StringUtils.isNotBlank(dto.getPublicKeyFilePath())) {
            organizationDTO.setPublicKeyFilePath(dto.getPublicKeyFilePath());
        }
        if (Objects.nonNull(dto.getDeliverCheckFlag())) {
            organizationDTO.setDeliverCheckFlag(dto.getDeliverCheckFlag());
        }
        if (Objects.nonNull(dto.getCompleteFlag())) {
            organizationDTO.setCompleteFlag(dto.getCompleteFlag());
        }
        if (StringUtils.isNotBlank(dto.getAdminName())) {
            organizationDTO.setAdminName(dto.getAdminName());
        }
        if (StringUtils.isNotBlank(dto.getCorpWallet())) {
            organizationDTO.setCorpWallet(dto.getCorpWallet());
        }
        if (Objects.nonNull(dto.getSmsPrice())) {
            organizationDTO.setSmsPrice(dto.getSmsPrice());
        }
        if (Objects.nonNull(dto.getFooter())) {
            organizationDTO.setFooter(dto.getFooter());
        } else {
            organizationDTO.setFooter(OrgFooterEnum.ORGANIZATION_FOOTER_NO.getType());
        }
        if (Objects.nonNull(dto.getNotifySalesFlag())) {
            organizationDTO.setNotifySalesFlag(dto.getNotifySalesFlag());
        } else {
            organizationDTO.setNotifySalesFlag(BooleanStatusEnum.YES.getStatus());
        }
        if (Objects.nonNull(dto.getInnerFlag())) {
            organizationDTO.setInnerFlag(dto.getInnerFlag());
        }
        if (StringUtils.isNotBlank(dto.getPaasConf())) {
            organizationDTO.setPaasConf(dto.getPaasConf());
        }
        if (StringUtils.isNotBlank(dto.getDistribution())) {
            organizationDTO.setDistribution(dto.getDistribution());
        }
        if (Objects.nonNull(dto.getDeliveryAuthType())) {
            organizationDTO.setDeliveryAuthType(dto.getDeliveryAuthType());
        }
        if (StringUtils.isNotBlank(dto.getContractUrls())) {
            organizationDTO.setContractUrls(dto.getContractUrls());
        }
        if (StringUtils.isNotBlank(dto.getRootGroupId())) {
            organizationDTO.setRootGroupId(dto.getRootGroupId());
        }
        if (StringUtils.isNotBlank(dto.getIndustryId())) {
            organizationDTO.setIndustryId(dto.getIndustryId());
        }
        if (StringUtils.isNotBlank(dto.getPackageId())) {
            organizationDTO.setPackageId(dto.getPackageId());
        }
        if (StringUtils.isNotBlank(dto.getFormalPackageId())) {
            organizationDTO.setFormalPackageId(dto.getFormalPackageId());
        }
        if (StringUtils.isNotBlank(dto.getTrialPackageId())) {
            organizationDTO.setTrialPackageId(dto.getTrialPackageId());
        }
        if (StringUtils.isNotBlank(dto.getPrivateKeyId())) {
            organizationDTO.setPrivateKeyId(dto.getPrivateKeyId());
        }
        if (StringUtils.isNotBlank(dto.getCheckSmtpId())) {
            organizationDTO.setCheckSmtpId(dto.getCheckSmtpId());
        }
        if (StringUtils.isNotBlank(dto.getParentId())) {
            organizationDTO.setParentId(dto.getParentId());
        }
        if (StringUtils.isNotBlank(dto.getIndustryCode())) {
            IndustryDTO industryDTO = industryGrpcService.getByCode(dto.getIndustryCode());
            // 设置industryId
            if (Objects.nonNull(industryDTO)) {
                organizationDTO.setIndustryId(industryDTO.getIndustryId());
            }
        }
        if (Objects.nonNull(dto.getBanLoginTrialExpiration())) {
            organizationDTO.setBanLoginTrialExpiration(dto.getBanLoginTrialExpiration());
        }
        if (Objects.nonNull(dto.getCheckExpiry())) {
            organizationDTO.setCheckExpiry(dto.getCheckExpiry());
        }
        if (StringUtils.isNotBlank(dto.getScenarioId())) {
            organizationDTO.setScenarioId(dto.getScenarioId());
        }
        if (Objects.nonNull(dto.getBackend())) {
            organizationDTO.setBackend(dto.getBackend());
        }
        // 私有化部署敏感词开关默认关闭
        organizationDTO.setSensitiveWordEnable(BooleanStatusEnum.NO.getStatus());
        return organizationDTO;
    }

    @Override
    public ServiceResult<OrganizationDTO> initOrganization(InitOrgRequestDTO dto) {
        OrganizationDTO organizationDTO = initOrgRequestDTOToDTO(dto);

        // 查找并更新公司
        String orgId;
        ServiceResult<OrganizationDTO> serviceResult = organizationService.selectByOrgCode(organizationDTO.getCode());
        if (null == serviceResult.getData()) {
            // 没查到创建公司
            ServiceResult<String> insert = organizationService.insert(organizationDTO);
            if (!insert.isSuccess()) {
                log.error("创建公司失败");
                return ServiceResult.fail("创建公司失败");
            }
            orgId = insert.getData();
        } else {
            // 查到更新公司
            orgId = serviceResult.getData().getOrgId();
            organizationDTO.setOrgId(orgId);
            ServiceResult<Boolean> update = organizationService.updateByPrimaryKeySelective(organizationDTO);
            if (Boolean.FALSE.equals(update.getData())) {
                log.error("更新公司失败");
                return ServiceResult.fail("更新公司失败");
            }
        }
        ServiceResult<OrganizationDTO> result = organizationService.selectByPrimaryKey(orgId);
        if (!result.isSuccess() || Objects.isNull(result.getData())) {
            log.error("查询公司失败 orgId ={}", orgId);
            return ServiceResult.fail("查询公司失败 orgId" + orgId);
        }
        return ServiceResult.success(result.getData());
    }

    @Override
    public ServiceResult<Void> transExpireDtToFreeExpireDt() {
        ServiceResult<List<OrganizationDTO>> allOrg = organizationService.getAllOrg();
        List<OrganizationDTO> dtos = allOrg.getData();
        for (OrganizationDTO dto : dtos) {
            if (null == dto.getFreeExpireTime()) {
                OrganizationDTO organizationDTO = new OrganizationDTO();
                organizationDTO.setOrgId(dto.getOrgId());
                organizationDTO.setFreeExpireTime(dto.getPackageExpireTime());
                organizationService.updateByPrimaryKeySelective(organizationDTO);
            }
        }
        return null;
    }

    @Override
    public ServiceResult<Boolean> setBrand() {
        List<String> codeLists = Arrays.asList("honda", "weltmeister", "wy-square", "weltmeister-ssi", "chanyi", "hzdsrmyy", "dhyx");
        ServiceResult<Boolean> result = null;
        ServiceResult<List<OrganizationDTO>> serviceResult = organizationService.listByCodes(codeLists);
        List<OrganizationDTO> orgList = serviceResult.getData();
        for (OrganizationDTO dto : orgList) {
            if (dto != null && dto.getFooter() != 1) {
                OrganizationDTO updateDto = new OrganizationDTO();
                updateDto.setOrgId(dto.getOrgId());
                updateDto.setFooter(2);
                result = organizationService.updateByPrimaryKeySelective(updateDto);
            }
        }
        return result;
    }

    @Override
    public ServiceResult<Void> setOrgInner() {
        // apps_mysql.user.init_data.set_org_inner
        if (!Boolean.TRUE.equals(settingProperties.getIsXm())) {
            organizationService.updateInnerFlagIsNullToFalse();
        } else {
            // 查询inner_flag为空的租户列表
            List<OrganizationDTO> orgInfos = organizationService.selectByInnerFlagIsNull();
            List<String> orgIdsTrue = new ArrayList<>();
            List<String> orgIdsFalse = new ArrayList<>();
            // 获取配置文件中内部公司信息
            Map<String, JSONArray> innerMap = FileUtils.readInnerUserFile(FileUtils.INNER_USER_FILE_PATH);
            for (OrganizationDTO orgInfo : orgInfos) {
                if (innerMap.get("INNER_ORG_CODE").contains(orgInfo.getCode())) {
                    orgIdsTrue.add(orgInfo.getOrgId());
                    UserDTO userDTO = new UserDTO();
                    userDTO.setOrgId(orgInfo.getOrgId());
                    userDTO.setInnerFlag(BooleanStatusEnum.YES.getStatus());
                    userService.updateByOrgIdSelective(userDTO);
                } else {
                    orgIdsFalse.add(orgInfo.getOrgId());
                }
            }

            if (CollectionUtils.isNotEmpty(orgIdsTrue)) {
                organizationService.updateInnerFlagByOrgIds(orgIdsTrue, BooleanStatusEnum.YES.getStatus());
                userService.updateInnerFlagByOrgIds(orgIdsTrue, BooleanStatusEnum.YES.getStatus());
            }
            if (CollectionUtils.isNotEmpty(orgIdsFalse)) {
                organizationService.updateInnerFlagByOrgIds(orgIdsFalse, BooleanStatusEnum.NO.getStatus());
            }
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<Void> manuallyInitOrg(String manuallyOrgCode, String manuallyOrgName) {
        // init_subsystem() 不迁移
//        initDataService.initModule();  // TODO 李坤磊 多模块拆分编译报错

        InitOrgRequestDTO org = new InitOrgRequestDTO();
        org.setCode(manuallyOrgCode);
        org.setName(manuallyOrgName);
        org.setContent(manuallyOrgName);
        org.setEmail("");
        org.setMobile("");
        org.setExpireDt(null);
        org.setIndustryCode(ApplicantTradeEnum.APPLICANT_TRADE_OTHER.getType().toString());
        ServiceResult<OrganizationDTO> serviceResult = initOrganization(org);
        if (serviceResult.isSuccess() && Objects.nonNull(serviceResult.getData())) {
            //获取orgId
            String orgId = serviceResult.getData().getOrgId();
            // 初始化系统管理员角色
            ServiceResult<UserRoleDTO> adminRoleAndPerms = initAdminRoleAndPerms(orgId);
            UserRoleDTO adminRole = adminRoleAndPerms.getData();
            if (adminRoleAndPerms.isSuccess() && Objects.nonNull(adminRole)) {
                // 初始化系统管理员用户并重置密码
                initAdminUser(adminRole, orgId);
                // 初始化短信模板和计算字段
//                initOrganizationAsyncTask(orgId);
                return ServiceResult.success();
            }
            return ServiceResult.fail(adminRoleAndPerms.getMsg());
        }
        return ServiceResult.fail(serviceResult.getMsg());
    }

    @Override
    public ServiceResult<Void> initAdminUser(UserRoleDTO roleDTO, String orgId) {
        // 新增系统管理员用户
        UserDTO userDTO = new UserDTO();
        userDTO.setOrgId(orgId);
        userDTO.setUserName("superadmin");
        userDTO.setName("超级管理员");
        userDTO.setContent("我是超级管理员，我无所不能^V^.");
        userDTO.setStatus(UserStatusEnum.ACTIVATED.getStatus());
        userDTO.setSalt(PwdUtil.genSalt());
        userDTO.setPassword(PwdUtil.getEncodePwd("admin123@idy.pwd", userDTO.getSalt()));
        userService.insert(userDTO);

        // 设置系统管理员用户的角色为系统管理员
        UserUserRoleDTO userUserRoleDTO = new UserUserRoleDTO();
        userUserRoleDTO.setOrgId(orgId);
        userUserRoleDTO.setUserId(userDTO.getUserId());
        userUserRoleDTO.setRoleId(roleDTO.getRoleId());
        userUserRoleService.insert(userUserRoleDTO);

        // 返回成功结果
        return ServiceResult.success();
    }

    @Override
    public void seqSynchronize() {
        int page = 1;
        int size = 1000;
        ArrayList<UserGroupDTO> seqAndOrgId = new ArrayList<>();

        HashMap<String, Integer> stringHashMap;
        while (seqAndOrgId.isEmpty() || seqAndOrgId.size() == size) {
            // 查询group表
            List<UserGroupDTO> groupDTOS = userGroupService.getSeqAndOrgId((page - 1) * size, size);
            if (CollectionUtils.isEmpty(groupDTOS)) {
                break;
            }

            // 组装数据
            HashMap<String, Integer> hashMap = new HashMap<>();
            for (UserGroupDTO userGroup : groupDTOS) {
                String key = userCacheUtil.buildKey(UserCacheKeyConstant.USER_GROUP_SEQ, userGroup.getOrgId());
                Integer val = userGroup.getSeq();
                hashMap.put(key, val);
            }
            stringHashMap = hashMap;

            // 刷redis
            try {
                userCacheUtil.multiSet(stringHashMap);
                log.info("redis刷新数据成功：" + stringHashMap);
            } catch (Exception e) {
                log.error("redis刷新数据失败" + stringHashMap);
            }

            // 刷sequence表
            try {
                sequenceService.batchUpdateSeqByCode(stringHashMap);
            } catch (Exception e) {
                log.error("sequence刷新数据失败" + stringHashMap);
                log.error("错误信息" + e);
            } finally {
                hashMap.clear();
                seqAndOrgId = (ArrayList<UserGroupDTO>) groupDTOS;
                page++;
            }
        }
    }

    @Override
    public void createCorporateWallet(String orgCode) {
        ServiceResult<OrganizationDTO> organizationDTOServiceResult = organizationService.selectByOrgCode(orgCode);
        OrganizationDTO org = organizationDTOServiceResult.getData();
        if (Objects.isNull(org)) {
            log.error("[User] 私有化部署初始化钱包 租户查询失败 orgCode:{}", orgCode);
            return;
        }
        // RED_PAPER_PLATFORM_CODE = env.str('RED_PAPER_PLATFORM_CODE', default=SINGLE_ORG['code'] if SINGLE_ORG else "bestcem")
        String platformCode = settingProperties.getRedPaperPlatformCode();
        if (ObjectUtils.isEmpty(platformCode)) {
            platformCode = singleOrgProperties.getCode();
            if (ObjectUtils.isEmpty(platformCode)) {
                platformCode = "bestcem";
            }
        }
        String corporateWalletId = userWalletGrpcService.createPlatformWallet(platformCode, org.getCode(), org);
        if (ObjectUtils.isEmpty(corporateWalletId)) {
            log.error("[User] 私有化部署初始化钱包 钱包创建失败 orgCode:{}", orgCode);
            return;
        }
        if (log.isInfoEnabled()) {
            log.info("[User] 私有化部署初始化钱包 钱包创建成功");
        }
        organizationDao.updateCorpWalletByOrgId(org.getOrgId(), corporateWalletId);
    }

}
